﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GradeBook.Models;

namespace GradeBook.Daos
{
    public class UserDao
    {
        public static List<User> Load()
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                return db.User.ToList();
            }
        }

        public static List<User> LoadSudentsByGroupId(int groupId)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                return (
                           from u in db.User
                           from rug in db.RelUserGroup
                           from r in db.Role
                           from rur in db.RelUserRole
                           where u.Id == rug.UserId
                           where rug.GroupId == groupId
                           where rur.UserId == u.Id
                           where rur.RoleId == r.Id
                           where r.Name == "STUDENT"
                           select u
                       ).ToList();
            }
        }

        public static User GetById(int id)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                return db.User.FirstOrDefault(u => u.Id == id);
            }
        }
        public static void Add(User user)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.User.AddObject(user);
                db.SaveChanges();
            }
        }
        public static void Update(User user)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.User.ApplyCurrentValues(user);
                db.SaveChanges();
            }
        }
        public static void Remove(int id)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                db.User.DeleteObject(db.User.FirstOrDefault(g => g.Id == id));
                db.SaveChanges();
            }
        }
    }
}